<?php
/**
 * 应用分类服务
 * @author haiqin
 *
 */ 
namespace Common\Logic;
class CatsLogic{
	
	private $m;
	private $group;

	function __construct(){
		$this->m = D('Cats');
		$this->group = D('CatsGroup');
	}
	
	public function _get_cats($groupid){
		$map['group_id'] = $groupid;
		$data = $this->m->where($map)->order('listorder desc')->select();
		return $data;
	}
	
	/**
	 * 固化app分类树存储
	 * @param unknown $appid
	 * @param unknown $groupid
	 */
	public function _update_cache_tree($groupid){
		$tree = new \Think\Tree();
	
		$data = $this->_get_cats($groupid);
	
		$tree->init($data);
		$treedata = $tree->get_tree_array(0, $str);
	
		F('Cats/group_'.$groupid,$treedata);
		return $treedata;
	}
	
	/**
	 * 根据分组ID找分类
	 * @param int $appid
	 * @param int $groupid
	 * @return tree
	 */
	public function _get_cats_tree($groupid){
		$treedata = F('Cats/group_'.$groupid);
		if(!$treedata) $treedata = $this->_update_cache_tree($appid,$groupid);
		return $treedata;
	}
	
	/**
	 * 根据分类key找分类
	 * @param int $appid
	 * @param string $groupkey
	 * @return data
	 */
	public function _get_cats_by_groupkey($groupkey){
		$map['group_key'] = $groupkey;
		$group = $this->group->where($map)->field('group_id')->find();
		return $this->_get_cats($group['group_id']);
	}
	
	/**
	 * 根据分类key找分类
	 * @param int $appid
	 * @param string $groupkey
	 * @return tree
	 */
	public function _get_cats_by_groupkey_tree($groupkey){
		$map['group_key'] = $groupkey;
		$group = $this->group->where($map)->field('group_id')->find();
		return $this->_get_cats_by_groupid($group['group_id']);
	}
	
	/**
	 * 获取select options
	 * @param unknown $appid
	 * @param unknown $groupid
	 * @return string
	 */
	public function _get_select_options($groupid,$curid){
		$tree = new \Think\Tree();
		$data = $this->_get_cats($groupid);
		foreach ($data as $r) {
			$r['selected'] = $r['id'] == $curid ? 'selected' : '';
			$array[] = $r;
		}
		$str = "<option value='\$id' \$selected>\$spacer \$cat_name</option>";
		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		return $select_categorys;
	}
	
	/**
	 * 获取select options
	 * @param unknown $appid
	 * @param unknown $groupkey
	 * @return string
	 */
	public function _get_select_options_by_groupkey($groupkey,$curid){
		$tree = new \Think\Tree();
		$data = $this->_get_cats_by_groupkey($groupkey);
		foreach ($data as $r) {
			$r['selected'] = $r['id'] == $curid ? 'selected' : '';
			$array[] = $r;
		}
		$str = "<option value='\$id' \$selected>\$spacer \$cat_name</option>";
		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		return $select_categorys;
	}
	
	/**
	 * 根据分类key找分类ID转成字符串
	 * @param unknown $groupkey
	 * @return string
	 */
	public function _get_cat_ids_string_by_groupkey($groupkey){
		$data = $this->_get_cats_by_groupkey($groupkey);
		foreach ($data as $r){
			$array[] = $r['id'];
		}
		return implode(',',$array);
	}
	
}
?>